package com.shiguiwu.springmybatis.javabase.nio.pipe;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * @description: 管道pipe
 *
 * 管道是 2 个线程之间的单向数据连接
 * 一个 source 通道（读取）和一个sink 通道（写入）
 * @author: stone
 * @date: Created by 2021/11/9 15:08
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.nio.pipe
 */
public class PipeTests {


    public static void main(String[] args) throws Exception {

        //1打开一个管道
        Pipe pipe = Pipe.open();

        //2获取sink 通道
        Pipe.SinkChannel sink = pipe.sink();

        //3创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        buffer.put("我是大傻逼".getBytes());

        buffer.flip();

        //4写入数据
        sink.write(buffer);

        //5创建一个source通道
        Pipe.SourceChannel source = pipe.source();

        //6创建一个读取缓冲区
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        int read = source.read(readBuffer);

        System.out.println(new String(readBuffer.array(), 0, read));

        //7关闭通道
        source.close();

        sink.close();


    }
}
